import O1HD from "../gameEngine";
import { CsvFileKind } from "../libs/CsvFileKind";
import SuperManager from "./superManager";

const {ccclass, property} = cc._decorator;

/**角色 */
export interface peopleArcheryRole{
    /**角色id */
    id:string,
    /**角色等级 */
    level:number,
}

export interface peopleArcheryData{
    /** 永久攻击加成 */
    atkAddition?:number,
    /** 永久回血加成 */
    revitAlize?:number,
    /** 无尽模式关卡数 */
    infinityLevel?:number,
    /** 已经解锁的角色 */
    unlockRole?:peopleArcheryRole[],
    /**当前模式的货币 */
    money?:number,
    /**每个角色看广告的次数 */
    adNum?:{[key:string]:number},
    /**当前使用的角色id */
    curUseRoleId?:string,
    /**当前的无尽关卡 */
    curInfinityLevel?:number,
}

@ccclass
export default class peopleArcheryManage extends SuperManager {

    async loadManager(){
        this.loadData();
    }

    normalPeopleData:peopleArcheryRole = {
        id:"1",
        level:1,
    }

    /**数据 */
    private _data:peopleArcheryData = {
        atkAddition:0,
        revitAlize:0,
        infinityLevel:0,
        unlockRole:[this.normalPeopleData],
        money:0,
        adNum:{},
        curUseRoleId:"1",
        curInfinityLevel:0,
    }

    /**初始数据 用于还原 */
    private _initData:string = "";

    /**缓存的key */
    private save_data_key = "user-data-peopleArchery-save-key";

    /**配置表是否加载完 */
    private configLoadFlag:boolean = false;

    getConfigComplete(){
        return this.configLoadFlag;
    }

    /**加载数据 */
    loadData(){
        this._initData = JSON.stringify(this._data);
        let dataStr = O1HD.getServices().localStorageSrv.getStorage(this.save_data_key) || this._initData;
        let data:peopleArcheryData = JSON.parse(dataStr);
        this.setData(data,false);
        let peoples = this.getData().unlockRole;
        for(let people of peoples){
            for(let key in this.normalPeopleData){
                if(people[key] == null){
                    if(this.normalPeopleData[key] instanceof Array){
                        people[key] = this.normalPeopleData[key].concat();
                    }else if(this.normalPeopleData[key] instanceof Object){
                        people[key] = JSON.parse(JSON.stringify(this.normalPeopleData[key]));
                    }else{
                        people[key] = this.normalPeopleData;
                    }
                }
            }
        }
        this.writeData();
    }

    /**获取数据 */
    getData(){
        return this._data;
    }

    /**
     * 设置数据
     * @param data 
     * @param isPlus 
     */
    setData(data:peopleArcheryData,isPlus:boolean = true){
        for(let key in data){
            let d = data[key];
            if(isPlus){
                if( d instanceof Array){
                    this._data[key] = this._data[key].concat(d);
                }else if( typeof d == "number") {
                    this._data[key] += d;
                }else{
                    this._data[key] = d;
                }
            }else{
                this._data[key] = d;
            }
        }
        this.writeData();
    }

    /**写入数据 */
    writeData(){
        O1HD.getServices().localStorageSrv.setStorage(this.save_data_key, JSON.stringify(this._data));
    }

    /**重置manager */
    resetManager(){
        this._data = JSON.parse(this._initData);
        this.writeData();
    }

    async loadConfig(){
        let roleIds:string[] = O1HD.getManagers().csvDataManager.getCsvIds(CsvFileKind.CsvFile.peopleArcheryRole);
        let roles:string[] = [];
        for(let id of roleIds){
            let file = O1HD.getManagers().csvDataManager.getCsvDataItem(CsvFileKind.CsvFile.peopleArcheryRole,id);
            let fileName:string = file["role_file"];
            roles.push(fileName);
        }
        let talentIds:string[] = O1HD.getManagers().csvDataManager.getCsvIds(CsvFileKind.CsvFile.peopleArcheryTalent);
        let talents:string[] = [];
        for(let id of talentIds){
            let file = O1HD.getManagers().csvDataManager.getCsvDataItem(CsvFileKind.CsvFile.peopleArcheryTalent,id);
            let fileName:string = file["talent_file"];
            talents.push(fileName);
        }

        let roleComplete:number = 0;
        let roleCount:number = roleIds.length;

        let talentComplete:number = 0;
        let talentCount:number = talentIds.length;

        let fun = ()=>{
            let isTrue:boolean = roleComplete >= roleCount && talentComplete >= talentCount;
            return isTrue;
        }

        return new Promise<void>(resolve=>{
            for(let role of roles){
                O1HD.getManagers().csvDataManager.loadCsvFile(`config/csv/peopleArchery/role/${role}`,false,()=>{
                    roleComplete ++;
                    this.configLoadFlag = fun();
                    if(this.configLoadFlag){
                        this.loadUnlockRole();
                        resolve();
                    }
                });
            }
            for(let talent of talents){
                O1HD.getManagers().csvDataManager.loadCsvFile(`config/csv/peopleArchery/talent/${talent}`,false,()=>{
                    talentComplete ++;
                    this.configLoadFlag = fun();
                    if(this.configLoadFlag){
                        this.loadUnlockRole();
                        resolve();
                    }
                });
            }
        });
    }

    addOneRole(roleId:string){
        let hasFlag:boolean = this.getRoleData(roleId) != null;
        if(hasFlag){
            return;
        }
        let data:peopleArcheryRole = <peopleArcheryRole>{};
        for(let key in this.normalPeopleData){
            let d = this.normalPeopleData[key];
            if(d instanceof Array){
                data[key] = d.concat();
            }else{
                data[key] = JSON.parse(JSON.stringify(d));
            }
        }
        data.id = roleId;
        this.setData({unlockRole:[data]},true);
    }


    getNormalPeopleData(){
        return this.normalPeopleData;
    }

    getRoleData(roleId:string){
        let data = this.getData().unlockRole.find((people)=>{
            return people.id == roleId;
        });
        // if(data)
        return data;
        // let pData:peopleArcheryRole = <peopleArcheryRole>{};
        // for(let key in this.normalPeopleData){
        //     if(this.normalPeopleData[key] instanceof Array){
        //         pData[key] = this.normalPeopleData[key].concat();
        //     }else{
        //         pData[key] = this.normalPeopleData[key];
        //     }
        // }
        // pData["id"] = roleId;
        // return pData;
    }

    loadUnlockRole(){
        let ids:string[] = O1HD.getManagers().csvDataManager.getCsvIds(CsvFileKind.CsvFile.peopleArcheryRole);
        for(let id of ids){
            let pData = O1HD.getManagers().csvDataManager.getCsvDataItem(CsvFileKind.CsvFile.peopleArcheryRole,id);
            let pUnlockType:string = pData.role_unlock_type;
            if(pUnlockType == "0"){
                this.addOneRole(id);
            }
        }
    }

    
    parseDataAsParam(data:any){
        let param =  Number(data?.option_param);
        if(isNaN(param)){
            param = 0;
        }
        return param;
    }

    parseDataAsParamText(data:any){
        let type:number = Number(data.param_type);
        let param:number = data.option_param;
        let str:string = "";
        if(type == 2 || type == 8 || type == 9 || type == 12 || type == 13 || type == 14 || type == 15 || type == 16 || type == 17 || type == 18 || type == 19 || type == 20|| type == 21 || type == 22){
            let num = Number((param * 100).toFixed(2));
            str = num > 0 ? "+" + num + "%" : num + "%";
        }else{
            str = `${param >=0 ? `+${param}` : param}`;
        }
        return str;
    }

    parseDataAsOptionText(data:any){
        let type:number = Number(data.param_type);
        let paramTextAry:string[] = [
            "生命",
            "攻击",
            "攻速",
            "射程",
            "子弹",
            "移速",
            "永久攻击",
            "回血",
            "射击伤害",
            "血量收益",
            "撞击吸血",
            "永久回血",
            "伤害减免",
            "暴击率",
            "暴击伤害",
            "血量上限",
            "回血增强",
            "BOSS降低血量",
            "五秒回复",
            "射击吸血",
            "关卡修为",
            "击败BOSS回血",            
            "子弹伤害",
        ];
        let text = paramTextAry[type];
        return text;
    }
    
    getOptionText(data:any){
        return this.parseDataAsOptionText(data) + this.parseDataAsParamText(data);
    }

}
